package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.entity.Order;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * IOrderService接口的业务逻辑实现类
 */
@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 库存服务的提供者
     */
    @DubboReference
    private IStockService stockService;
    /**
     * 购物车服务的提供者
     */
    @DubboReference
    private ICartService cartService;

    /**
     * 新增订单的业务处理层方法
     * @param orderAddDTO
     */
    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //1. 这里先要进行减少数据库中库存的操作 调用stock模块
        StockReduceCountDTO countDTO = new StockReduceCountDTO();
        countDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        countDTO.setReduceCount(orderAddDTO.getCount());
        stockService.updateStockCount(countDTO);
        //2. 从购物车中删除用户选中的闪频 调用cart模块
        cartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        //测试，手动抛出异常,判断分布式事务是否开启成功
        if(Math.random()>0.5){
            log.info("出发了>0.5");
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"故意抛出的异常(不是代码错误)");
        }
        //3. 上述操作完成后，在进行订单的新增
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO,order);
        int i = orderMapper.insertOrder(order);
        log.info("成功添加了{}条数据",i);
    }

}
